<?php
/**
 * Service层基础封装
 *
 * @property CI_Loader $load
 */
class MY_Service
{
    protected $return = [];

    public function __construct()
    {
        log_message('debug', "Service Class Initialized");

    }

    function __get($key)
    {
        $CI = & get_instance();
        return !empty($CI->$key) ? $CI->$key : '';
    }
    /**
     * 响应结果
     * @author duanlang<duanlang@iyene.com>
     * @param  integer $code [description]
     * @param  string $data [description]
     * @return array
     */
    public function response($code = 0, $data = ''){
        $result = array(
            'code'  =>  $code,
            'data'  => $data
        );
        return $result;
    }

    /**
     * 爱聚记录文件日志(便于后期跟踪查询)
     *
     * @param  [type] $filename [日志名]
     * @param  [type] $logData  [日志数据]
     * @param  [type] $type     [日志类型]
     * @return [type]           [description]
     */
    public function log($filename,$logData, $type = 'default')
    {
        $logPath = '/data/logs/crm/'.$type;
        //检测日志文件是否存在
        if(!is_dir($logPath))
        {
            mkdir($logPath, 0777, true);
        }

        $logPath = $logPath.'/'.$filename;
        $logData = var_export($logData, true);
        $logData = "[".date("Y/m/d h:i:s")."]: ".$logData;

        //写入日志
        file_put_contents($logPath, $logData, FILE_APPEND);
    }

    /**
     * 输出json,或jsonp
     * @param  integer $code   [状态码 > 1 处理正确结果，< 1 错误]
     * @param  mixed  $result [返回结果]
     */
    public function responseSer($code = 1, $result = ''){
        if (isset($_SERVER['HTTP_ORIGIN'])) {
            //跨域请求Ajax请求，多个直接加数组值
            $origin = array('http://crm.ecbao.cn', 'http://scrm.ecbao.cn','https://crm.ecbao.cn', 'https://scrm.ecbao.cn');
            $access_origin = in_array($_SERVER['HTTP_ORIGIN'], $origin) ? $_SERVER['HTTP_ORIGIN'] : '';
            header('Access-Control-Allow-Origin: *');
            header('Access-Control-Allow-Methods:POST');
            header('Access-Control-Allow-Headers: xm-token,xm-api-type,App-Key,Access-Token');
        }
        $response = json_encode(array(
            'code' => $code,
            'data' => $result
        ));

        //jsonp处理
        $callback = $this->input->get('callback');
        if ($callback) {
            header('Content-Type: application/javascript');
            die($callback . '('. $response .')');
        } else {
            header('Content-Type: application/json');
            die($response);
        }
    }
}
